/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yunhoo.base.bean;

import com.yunhoo.base.db.impl.CostItemImpl;
import com.yunhoo.base.model.CostItem;
import com.yunhoo.base.model.MsgModel;

import com.yunhoo.sys.db.util.IbatisTemplate;
import com.yunhoo.sys.util.common.StringTool;
import com.yunhoo.sys.util.common.ToolKit;
import com.yunhoo.sys.util.tree.TreeRule;
import com.yunhoo.sys.util.tree.TreeUtil;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.html.HtmlInputText;
import javax.faces.context.FacesContext;
import org.richfaces.component.UIDataTable;
import org.richfaces.event.TreeSelectionChangeEvent;
import org.richfaces.model.TreeNode;
import org.richfaces.model.TreeNodeImpl;

/**
 *
 * @author Administrator
 */
@ManagedBean(name = "coitem")
@SessionScoped
public class CostItemBean {

    private CostItem coitem = new CostItem();
    private TreeNode rootNode = null;
    private int counter = 1;
    private UIDataTable data = null;
    private HtmlInputText deptCode = new HtmlInputText();
    private boolean editAble = false;
    private boolean showAble = true;
    private boolean addOrUpdate = false;
    private List<CostItem> newlist = new ArrayList<CostItem>();
    private static String[] rule = TreeRule.getEconomicTreeRule();

    public CostItemBean() {
    }

    private void loadTree() {       
        newlist = new ArrayList<CostItem>();
        rootNode = new TreeNodeImpl();
        List<CostItem> list = CostItemImpl.geteconomic();         
        TreeUtil.addNode(list, rootNode, rule);
    }

//    private void addNodes(List<CostItem> depli, TreeNode node) {
//        CostItem cost = new CostItem();
//        for (int i = 0; i < depli.size(); i++) {   
//            CostItem depart = depli.get(i);
//            String isend = depart.getIsEnd();
//            TreeNodeImpl nodeImpl = new TreeNodeImpl();
//            nodeImpl = new MenuTreeNodeImpl(false, depart);
//            //nodeImpl.setData(depart);
//            node.addChild(new Integer(counter), nodeImpl);
//            counter++;
//            if (isend.endsWith("0")) {
//               cost.setCostcode(depart.getCostcode().trim());
//               cost.setGradeLevel(depart.getGradeLevel()+1);
//               List subDeptList = CostItemImpl.getsubeconomic(cost);
//               addNodes(subDeptList, nodeImpl);
//            }
//        }
//    }
    public void selected(TreeSelectionChangeEvent event) {
        System.out.println("selected!!!");
        editAble = false;
        showAble = true;
        // HtmlTree tree = (HtmlTree)event.getComponent();
        // coitem = (CostItem)tree.getRowData();
        coitem = (CostItem) TreeUtil.listener(event);
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void addDepartment() {
        showAble = false;
        editAble = false;
        addOrUpdate = true;
        coitem = new CostItem();
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void savaDepartment() {
        String dcode = coitem.getCode();
        String rule = CostItemImpl.getCodeRule();

        if (StringTool.setDeptGrade(rule, dcode) > 0) {
            coitem.setGrade(StringTool.setDeptGrade(rule, dcode));
            if (addOrUpdate) {
                insert();
            }
            if (!addOrUpdate) {  //修改
                System.out.println("进入修改判断");
                update();
            }
        } else {
            System.out.println("插入数据不符合规范~");
        }
        loadTree();
        initStatus();
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void insert() {
        List temp = CostItemImpl.checkDepartmentRepeat(coitem);//查询节点是否重复
        if (coitem.getGrade() != 1) {
            CostItem checkParent = CostItemImpl.checkDepartmentParent(coitem);
            if (temp.size() == 0) {  //节点不重复
                if (checkParent != null) {
                    if (checkParent.getIsEnd().equals(1)) { //父节点IsEnd是1的改为0;
                        checkParent.setIsEnd(0);
                        CostItemImpl.updateDeptIsEnd(checkParent);
                    }
                    coitem.setIsEnd(1);
                    CostItemImpl.insertDept(coitem);
                } else {
                    System.out.println("上级不存在!!!");
                }
            } else {
                System.out.println("insert~~代码或名称已存在!!!");
            }
        } else {
            if (temp.size() == 0) {
                coitem.setIsEnd(1);
                CostItemImpl.insertDept(coitem);
            } else {
                System.out.println("insert~~代码或名称已存在!!!");
            }
        }
    }

    public void update() {
        List<CostItem> updateli = CostItemImpl.checkEconomicRepeatForUpdate(coitem);
        String name = coitem.getName().trim();
        if (!(updateli != null && updateli.size() > 0)) {    //不重复
            CostItemImpl.updateDepartment(coitem);
        } else {
            System.out.println("update~~代码或名称已存在!!!");
            coitem.setName(name);
        }
    }

    public void deleteDepartment() {
        /** 末节点直接删除
         * 非末节点不允许删除
         * 节点删除后,其父节点如果无其他子节点,修改其父节点 isEnd属性值为"1"
         */
        CostItem parent = CostItemImpl.checkDepartmentParent(coitem);//父节点

        if (!(coitem.getIsEnd().equals(0))) {
            CostItem predele = new CostItem();//兄弟节点
            if (parent == null) {                 //删除根节点
                CostItemImpl.deleteDepartment(coitem);
            } else {                               //删除非根节点
                predele.setCode(parent.getCode().trim());
                predele.setGrade(coitem.getGrade());

                List list = CostItemImpl.getDeptSameLevel(predele);//查询兄弟节点
                if (list.size() == 1) {
                    //要删除节点,如果无兄弟节点,修改其父节点 isEnd属性为"1"
                    parent.setIsEnd(1);
                    CostItemImpl.updateDepartment(parent);
                }
                CostItemImpl.deleteDepartment(coitem);
            }
        } else {
             ToolKit.msgs_err("非末节点,不可删除");
        }
        loadTree();
        initStatus();
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void checkDeteleCostitem() {
        MsgModel msg = CostItemImpl.selectCostMsg(coitem.getCode().trim());
        
        if (msg.getMsg().equals("") && msg.getMsg2().equals("") && msg.getMsg3().equals("")) {
            deleteDepartment();
        } else {
            ToolKit.msgs_err("已在表" + msg.getMsg() + "  " + msg.getMsg2() + "  " + msg.getMsg3() + "中使用");
        }
    }

    public CostItem getGradeLevel(String code) {
        CostItem result = new CostItem();
        String[] arr = {"3", "5", "7"};
        System.out.println("CostItem的Costcode:" + code.trim());
        for (int i = 0; i < arr.length; i++) {
            if (code.trim().length() == Integer.parseInt(arr[i])) {
                result.setGrade(i + 1);
                break;
            }
        }
        System.out.println("rusult level:" + result.getGrade());
        return result;
    }

    public void initStatus() {
        showAble = true;
        editAble = false;
        addOrUpdate = true;
    }

    public void updateDept() {
        deptCode.setReadonly(true);
        showAble = false;
        editAble = true;
        addOrUpdate = false;
        System.out.println("准备进入修改判断");
        FacesContext.getCurrentInstance().renderResponse();
    }
    //getter and setter

    public int getCounter() {
        return counter;
    }

    public void setCounter(int counter) {
        this.counter = counter;
    }

//    public TreeNode getRootNode() {
//         if (this.rootNode == null) {
//            loadTree();
//        }
//        return rootNode;
//    }
    public TreeNode getRootNode() {
        if (this.rootNode == null) {
            loadTree();
        }
        return rootNode;
    }

    public void setRootNode(TreeNode rootNode) {
        this.rootNode = rootNode;
    }

    public CostItem getCoitem() {
        return coitem;
    }

    public void setCoitem(CostItem coitem) {
        this.coitem = coitem;
    }

    public HtmlInputText getDeptCode() {
        return deptCode;
    }

    public void setDeptCode(HtmlInputText deptCode) {
        this.deptCode = deptCode;
    }

    public boolean isEditAble() {
        return editAble;
    }

    public void setEditAble(boolean editAble) {
        this.editAble = editAble;
    }

    public boolean isShowAble() {
        return showAble;
    }

    public void setShowAble(boolean showAble) {
        this.showAble = showAble;
    }

    public UIDataTable getData() {
        return data;
    }

    public void setData(UIDataTable data) {
        this.data = data;
    }

    public List<CostItem> getNewlist() {
        return newlist;
    }

    public void setNewlist(List<CostItem> newlist) {
        this.newlist = newlist;
    }

    public boolean isAddOrUpdate() {
        return addOrUpdate;
    }

    public void setAddOrUpdate(boolean addOrUpdate) {
        this.addOrUpdate = addOrUpdate;
    }
    //* * end * *
}
